#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update: 2010/10/30 10:53:52

'''docstring
'''

__revision__ = '0.1'
__author__ = 'lxd'
import time
import random
import hashlib

def getRGB(integer):
    '''get color in rgb format
    >>> getRGB(13998675)
    'D59A53'
    >>> getRGB(9435)
    '0024DB'
    >>> getRGB(0)
    '000000'
    '''
    str = hex(integer).upper()
    if str[-1] == 'L':
        str = str[:-1]
    str = str[2:]
    len_str = len(str) 
    if len_str < 6:
        return '0' * (6 - len_str) + str
    else:
        return str

def getHexRGBFromDecimal(decimals):
    '''
    >>> getHexRGBFromDecimal((83,154,213))
    'D59A53'
    '''
    r = ''
    for i in decimals:
        r = hex(i).upper()[2:] + r
    return r

def checkColor(decimals,color):
    '''
    >>> checkColor((83,154,213),'D59A53')
    True
    '''
    if int(color[:2],16) != decimals[2]:
        return False
    if int(color[2:4],16) != decimals[1]:
        return False
    if int(color[4:],16) != decimals[0]:
        return False
    return True

def sleep():
    '''
    >>> sleep()
    '''
    time.sleep(random.random()+0.3)

def createBitsList(bits,width,height):
    '''
    >>> bits = '001122334455667788990011223344556677889900112233'
    >>> createBitsList(bits,2,3)
    [['001122', '445566'], ['889900', '223344'], ['667788', '001122']]
    ''' 
    assert width*height ==len(bits)/8
    r = []
    for j in range(height):
        l = []
        for i in range(width):
            start = j*width*8+i*8
            l.append(bits[start:start+6])
        r.append(l)
    return r

def findRegionFlag(lst,flag,step = 1):
    '''从左向右，从上向下查找
    像素坐标与矩阵坐标正好相反，所以矩阵坐标需要转置一下
    >>> lst = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,1,0]]
    >>> print findRegionFlag(lst,1)
    (3, 4)
    >>> #没有找到点
    >>> lst = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
    >>> print findRegionFlag(lst,1)
    (-1, -1)
    >>> #有步长
    >>> lst = [[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
    >>> print findRegionFlag(lst,1,2)
    (-1, -1)
    '''
    width = len(lst[0])
    height = len(lst)
    for j in range(0,height,step):
        for i in range(0,width,step):
            if lst[j][i] == flag:return i,j
    return -1,-1

def findCenterFlag(lst,flag,step = 1):
    '''从中心向周围查找
    像素坐标与矩阵坐标正好相反，所以矩阵坐标需要转置一下
    >>> #一般矩阵（5,5）中心点正好在中心上
    >>> lst = [[0,1,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
    >>> print findCenterFlag(lst,1)
    (1, 0)
    >>> #没有找到点
    >>> lst = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
    >>> print findCenterFlag(lst,1)
    (-1, -1)
    >>> #中心点不在中心上,偏右偏下
    >>> lst = [[0,0,0,0,0,0],[0,0,0,0,0,1],[0,0,0,0,0,0],[0,0,0,0,0,0]]
    >>> print findCenterFlag(lst,1)
    (5, 1)
    >>> #按步长找
    >>> lst = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,1,0,0,0,0],[0,0,0,0,0,0]]
    >>> print findCenterFlag(lst,1,2)
    (1, 2)
    '''
    width = len(lst[0])
    height = len(lst)
    x = width/2
    y = height/2
    visitCount = 0
    moveValue = {'left':(-step ,0),'right':(step,0),'up':(0,-step),'down':(0,step)}
    aspect = 'up'
    count = 1
    visit = False
    while visitCount<width*height:
        for i in range(count):
            if x>=0 and x<width and y>=0 and y<height:
                if lst[y][x] == flag:
                    return x,y
                visitCount += 1
                visit = True
            x += moveValue[aspect][0]
            y += moveValue[aspect][1]
        if aspect == 'left':
            if not visit: return -1,-1
            visit = False
            aspect = 'up'
            count += 1
        elif aspect == 'right':
            aspect = 'down'
            count += 1
        elif aspect == 'up':
            aspect = 'right'
        elif aspect == 'down':
            aspect = 'left'
    return -1,-1

def splitColors(colors):
    '''
    >>> colors = '1,2,3|4,5,6'
    >>> splitColors(colors)
    [[1, 4], [2, 5], [3, 6]]
    '''
    color = colors.split('|')
    xs = map(int, color[0].split(','))
    ys = map(int, color[1].split(','))

    r = []
    for i in range(len(xs)):
        r.append([xs[i],ys[i]])
    return r

#def getRGBOffsetColor(offset_color):
    #'''没有转换偏移色
    #>>> offset_color = '9|38|5F5404,21|36|574D12'
    #>>> getRGBOffsetColor(offset_color)
    #'9|38|04545F,21|36|124D57'
    #'''
    #r = []
    #for offset in offset_color.split(','):
        #point= offset.split('|')
        #color = point[2]
        #c = color[4:]+color[2:4]+color[:2]
        #new_sets = '%s|%s|%s' %(point[0],point[1],c)
        #r.append(new_sets)
    #return ','.join(r)

def splitMultiColorFromStr(colors):
    '''
    >>> colors = '263a17,1|8|344b13,14|3|5a724e'
    >>> color,offset_color = splitMultiColorFromStr(colors)
    >>> color
    '263a17'
    >>> offset_color
    '1|8|344b13,14|3|5a724e'
    '''
    lst = colors.split(',')
    return lst[0],','.join(lst[1:])

def saveData(filename, data):
    f = open(filename, 'w')
    f.write(data)
    f.close()

def loadData(filename):
    f = open(filename, 'r')
    data = f.read()
    f.close()
    return data

def getMD5(str):
    m = hashlib.md5()
    m.update(str)
    return m.hexdigest()
    
def getKeyOfEmail(email):
    lst = email.split('@')
    str = lst[1]+'34*23'+lst[0]
    return getMD5(str)

def loopWithTime(break_fun=None, loop_times=5, sleep_time=1):
    """每隔sleep_time秒尝试做某事，共尝试loop_times次，如果发生break_fun则马上停止
    被装饰者必须返回True或者False
    loop_times循环次数
    sleep_time每次循环等待时间
    break_fun随时中断函数
    """
    def wrapper(fun):
        def _():
            times= 0
            while times< loop_times:
                if break_fun and callable(break_fun):break_fun()
                if fun():
                    return True
                else:
                    times += 1 
                    time.sleep(sleep_time)
            return False
        return _
    return wrapper

def string(value):
    """
    >>> string(2)
    '2'
    """
    try:
        return str(value)
    except UnicodeEncodeError:
        return value

if __name__ == '__main__':
    import doctest
    doctest.testmod()
